const jwt = require("jsonwebtoken");
const { PUBLIC_KEY } = require("../app/config");
const userService = require("../service/user.service");
const errorType = require("../constants/error-type");
const md5Password = require("../utils/password-md5");
const verifyLogin = async (ctx, next) => {
  try {
    const { name, password } = ctx.request.body;
    const result = await userService.getUserByName(name);
    verifyFn(ctx, next, result, "name", password);
  } catch (error) {
    console.log(error);
  }
};
const verifyCellphoneLogin = async (ctx, next) => {
  try {
    const { cellphone, password } = ctx.request.body;
    const result = await userService.getUserByCellphone(cellphone);
    verifyFn(ctx, next, result, "cellphone", password);
  } catch (error) {
    console.log(error);
  }
};
const verifyEmailLogin = async (ctx, next) => {
  try {
    const { email, password } = ctx.request.body;
    const result = await userService.getUserByEmail(email);
    verifyFn(ctx, next, result, "email", password);
  } catch (error) {
    console.log(error);
  }
};

async function verifyFn(ctx, next, result, type, password) {
  if (!result.length) {
    switch (type) {
      case "name":
        return ctx.app.emit("error", errorType.USER_NAME_IS_NOT_EXISTS, ctx);
      case "email":
        return ctx.app.emit("error", errorType.EMAIL_IS_NOT_EXISTS, ctx);
      case "cellphone":
        return ctx.app.emit("error", errorType.CELLPHONE_IS_NOT_EXISTS, ctx);
    }
  }
  ctx.user = result[0];
  if (result[0].password !== md5Password(password)) {
    return ctx.app.emit("error", errorType.PASSWORD_IS_INCORRECT, ctx);
  }
  await next();
}
const verifyAuth = async (ctx, next) => {
  try {
    const authorization = ctx.header.authorization;
    if (!authorization) {
      return ctx.app.emit("error", errorType.UNAUTHORIZATION, ctx);
    }
    const token = authorization.replace("Bearer ", "");
    const result = jwt.verify(
      token,
      PUBLIC_KEY,
      {
        algorithms: ["RS256"]
      },
      null
    );
    ctx.user = { ...result };
    await next();
  } catch (error) {
    return ctx.app.emit("error", errorType.UNAUTHORIZATION, ctx);
  }
};

module.exports = {
  verifyLogin,
  verifyCellphoneLogin,
  verifyEmailLogin,
  verifyAuth
};
